from fastapi import FastAPI, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
import os

# 创建FastAPI应用
app = FastAPI(title="配置信息", description="")

origins = ["*"]

# 添加CORS中间件，允许指定域名访问
app.add_middleware(
    CORSMiddleware,
    # allow_origins=['http://file.uhsea.com'],  # 允许所有域名访问
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 定义文件路径
FILE_PATH = "url.txt"

# 文本内容大小限制（1KB）
MAX_CONTENT_SIZE = 1024

@app.get("/api", summary="服务根路径")
async def root():
    """服务根路径，返回服务基本信息"""
    return {"message": "文本存储服务", "endpoints": ["/upload/", "/get/"]}

@app.post("/api/upload", summary="上传文本内容")
async def upload_text(request: Request):
    """上传文本内容并保存到url.txt文件中"""
    try:
        # 获取请求体
        data = await request.json()
        
        # 检查是否有content字段
        if "content" not in data:
            return JSONResponse(
                status_code=400,
                content={"message": "缺少content字段"}
            )
        
        content = data["content"].strip()
        
        # 检查内容大小
        if len(content.encode('utf-8')) > MAX_CONTENT_SIZE:
            return JSONResponse(
                status_code=400,
                content={"message": "文本内容必须小于1KB"}
            )

        # 将内容写入文件
        with open(FILE_PATH, "w", encoding="utf-8") as file:
            file.write(content)
        
        return {"message": "文本内容已成功保存"}
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"保存文件时出错: {str(e)}")

@app.get("/api/get", summary="获取文本内容")
async def get_text():
    """获取url.txt文件中的文本内容，包括url、logo和title"""
    try:
        # 检查文件是否存在
        if not os.path.exists(FILE_PATH):
            return {"url": "", "logo": "", "title": ""}
        
        # 读取文件内容
        with open(FILE_PATH, "r", encoding="utf-8") as file:
            lines = file.readlines()
            
        # 确保文件至少有3行
        while len(lines) < 3:
            lines.append("")
            
        # 去除每行末尾的换行符
        url = lines[0].strip()
        logo = lines[1].strip()
        title = lines[2].strip()
        
        return {"url": url, "logo": logo, "title": title, "message": "CORS Allowed"}
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"读取文件时出错: {str(e)}")

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)
